<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 会员促销类
 * @package  module/base/promotion
 * @subpackage
 * @author  create by allen.qiang
 * @version 1.0
 */

class promotionCustomer {

    /**
     * 查询会员促销信息
     * @param array $arg_array
     * @return array|null
     */
    public function searchPromotionCustomerInfo( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //活动标题
        if (isset($arg_array['title']) &&  !empty($arg_array['title']) ) {
            $sql .= ' AND title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['title']).'%';
        }
        //促销方式
        if (isset($arg_array['manner']) && is_numeric($arg_array['manner'])) {
            $sql .= ' AND manner = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['manner'];
        }

        //活动类型
        if (isset($arg_array['source']) && is_numeric($arg_array['source'])) {
            $sql .= ' AND source = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['source'];
        }

        //促销类型
        if (isset($arg_array['type']) && is_numeric($arg_array['type'])) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

        //促销日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND startDate <= ? AND endDate >= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_customer ' . $sql;
            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            $arg_array['count'] = 0;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //查询分类信息
        $search_sql = 'SELECT * FROM promotion_customer ' . $sql;
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array)
            return null;

        $item_array = array();

        foreach($temp_item_array as &$item) {
            $item_array[] = array(
                'creator'  => $item->creator,
                'createTime' => $item->createTime,
                'promotionID' => $item->promotionID,
                'title' => $item->title,
                'source' => $item->source,
                'startDate' => $item->startDate,
                'endDate' => $item->endDate,
                'type' => $item->type,
                'points' => $item->points,
                'useFlg' => $item->useFlg
            );

        }

        return $item_array;

    }

    /**
     * 保存会员促销
     * @param $arg_array
     * @return array
     */
    public function savePromotionCustomerInfo( $arg_array ) {

        global $G_SHOP;

        //参数检查
        if(!isset($arg_array['promotionID'] ,$arg_array['title'],$arg_array['source'],$arg_array['startDate'] ,$arg_array['endDate'],$arg_array['type'] , $arg_array['creator']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        $type  	   	 = $arg_array['type'] ;
        $source 	 = $arg_array['source'] ;
        $title 	   	 = htmlspecialchars(trim($arg_array['title'])) ;
        $startDate 	 = $arg_array['startDate'] ;
        $endDate   	 = $arg_array['endDate'] ;
        $useFlg  	 = $arg_array['useFlg'] ;
        $promotionID = $arg_array['promotionID'] ;

        //规则参数查检
        $error_msg = '' ;

        if($title == '')
            $error_msg .= '促销活动标题不能为空</br>' ;

        if(!in_array($source , array(1,2,3,4,5,6,7)))
            $error_msg .= '活动类型参数错误</br>';

        if(!in_array($type , array(1,2)))
            $error_msg .= '促销类型参数错误</br>';

        if($startDate == '' || $endDate == '')
            $error_msg .= '促销开始和结束时间不能为空</br>' ;

        if($startDate > $endDate)
            $error_msg .= '促销开始时间不能大于结束时间</br>' ;

        if(!in_array($useFlg , array(0,1)))
            $error_msg .= '使用状态参数错误</br>';

        if( $error_msg != '' )
            return array( 'code' => 400, 'message' => $error_msg );

        $points = '';         //记录积分
        $couponArray = '';  //记录优惠券信息

        if($type == 1){
            if(!isset($arg_array['points']))
                return array( 'code' => 400, 'message' => '赠送积分不能为空' );

            $points = $arg_array['points'];

        }elseif( $type == 2 ){
            if(!isset( $arg_array['couponLine'] ))
                return array( 'code' => 400, 'message' => '缺少参数' );

            $couponArray  = $arg_array['couponLine'];//优惠券明细

        }

        $G_SHOP->DBCA->beginTransaction() ;
        try{

            if($promotionID != ""){

                //检查优惠券明细
                $promotion_coupon = array();
                if($couponArray){
                    foreach ($couponArray as $couponVal){

                        //检查优惠券数量是否正确
                        if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
                            throw new Exception('优惠券的张数必须为正整数', 400) ;

                        if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
                            throw new Exception('优惠券的编号必须为正整数', 400) ;

                        $accountCoupon = new entity('promotion_coupon');
                        $accountCoupon->couponID = $couponVal[1];
                        if(!$G_SHOP->DBCA->fetch($accountCoupon))
                            throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;

                        $coupon_detail = new entity('promotion_customer_coupon');
                        $coupon_detail->creator     = $arg_array['creator'];
                        $coupon_detail->promotionID = $promotionID;
                        $coupon_detail->couponID    = $couponVal[1];
                        $coupon_detail->couponNum   = $couponVal[0];
                        $coupon_detail->couponName  = $accountCoupon->couponName ;

                        $promotion_coupon[] = $coupon_detail;
                    }
                }

                //保存促销信息
                $save_promotion_customer = new entity('promotion_customer') ;
                $save_promotion_customer->promotionID 	 = $promotionID ;
                if(!$G_SHOP->DBCA->fetch($save_promotion_customer))
                    throw new Exception(sprintf('促销活动号「%s」的促销不存在' ,$promotionID), 400) ;

                $save_promotion_customer->title   	  	 = $arg_array['title'] ;
                $save_promotion_customer->startDate  	 = $arg_array['startDate'] ;
                $save_promotion_customer->endDate	  	 = $arg_array['endDate'] ;
                $save_promotion_customer->source		 = $arg_array['source'] ;
                $save_promotion_customer->type		  	 = $type ;
                $save_promotion_customer->useFlg		 = $useFlg;

                if( $points )
                    $save_promotion_customer->points     = $points ;

                $G_SHOP->DBCA->save($save_promotion_customer);

                //删除老的优惠券详情
                $G_SHOP->DBCA->stmt_query('DELETE FROM promotion_customer_coupon WHERE promotionID=?' , 'i' , $promotionID);

                //保存优惠券明细
                if($promotion_coupon) {
                    foreach ($promotion_coupon as &$c_l) {
                        $G_SHOP->DBCA->save($c_l) ;
                    }
                }

                $G_SHOP->DBCA->commit() ;
                return array( 'code' => 200, 'message' => '会员促销更新成功' );
            }else{

                //生成促销活动号
                $promotionID = promotion_seq_no() ;

                //检查优惠券明细
                $promotion_coupon = array();
                if($couponArray){
                    foreach ($couponArray as $couponVal){

                        //检查优惠券数量是否正确
                        if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
                            throw new Exception('优惠券的张数必须为正整数', 400) ;

                        if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
                            throw new Exception('优惠券的编号必须为正整数', 400) ;

                        $accountCoupon = new entity('promotion_coupon');
                        $accountCoupon->couponID = $couponVal[1];
                        if(!$G_SHOP->DBCA->fetch($accountCoupon))
                            throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;

                        $coupon_detail = new entity('promotion_customer_coupon');
                        $coupon_detail->creator     = $arg_array['creator'];
                        $coupon_detail->promotionID = $promotionID;
                        $coupon_detail->couponID    = $couponVal[1];
                        $coupon_detail->couponNum   = $couponVal[0];
                        $coupon_detail->couponName  = $accountCoupon->couponName ;

                        $promotion_coupon[] = $coupon_detail;
                    }
                }

                //保存促销信息
                $save_promotion_customer = new entity('promotion_customer') ;
                $save_promotion_customer->creator    	 = $arg_array['creator'] ;
                $save_promotion_customer->title   	  	 = $arg_array['title'] ;
                $save_promotion_customer->startDate  	 = $arg_array['startDate'] ;
                $save_promotion_customer->endDate	  	 = $arg_array['endDate'] ;
                $save_promotion_customer->source		 = $arg_array['source'] ;
                $save_promotion_customer->type		  	 = $type ;
                $save_promotion_customer->promotionID 	 = $promotionID ;
                $save_promotion_customer->useFlg		 = $useFlg;

                if( $points )
                    $save_promotion_customer->points     = $points ;

                $G_SHOP->DBCA->save($save_promotion_customer);

                //保存优惠券明细
                if($promotion_coupon) {
                    foreach ($promotion_coupon as &$c_l) {
                        $G_SHOP->DBCA->save($c_l) ;
                    }
                }

                $G_SHOP->DBCA->commit() ;
                return array( 'code' => 200, 'message' => '会员促销保存成功' );
            }

        }catch (Exception $e) {

            $G_SHOP->DBCA->rollBack() ;
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询会员促销活动领取记录
     * @param $args_array
     * @return array|null
     */
    public function searchCustPromotionLog( &$args_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($args_array['promotionID']) && quanli_is_int($args_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $args_array['promotionID'];
        }

        //会员号
        if (isset($args_array['pcustID']) && quanli_is_int($args_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $args_array['pcustID'];
        }

        //日期
        if (isset($args_array['date']) || is_date($args_array['date'])) {
            $sql .= ' AND date = ?';
            $params_type .= 's';
            $params_array[] = $args_array['date'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_customer_log ' . $sql;
            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            $arg_array['count'] = 0;

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //查询信息
        $search_sql = 'SELECT * FROM promotion_customer_log ' . $sql;
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array)
            return null;

        $item_array = array();

        foreach($temp_item_array as &$item) {
            $item_array[] = array(
                'createTime' => $item->createTime,
                'promotionID' => $item->promotionID,
                'pcustID' => $item->pcustID,
                'date' => $item->date
            );
        }

        return $item_array;

    }

    /**
     * 查询会员促销赠送的优惠券信息
     * @param int $promotionID 促销id
     * @return array|null
     */
    public function searchCustPromotionCoupon( $promotionID ) {

        global $G_SHOP;

        if (!isset($promotionID) || !quanli_is_int($promotionID)) {
            return null;
        }

        //查询信息
        $search_sql = 'SELECT * FROM promotion_customer_coupon WHERE promotionID = ?';
        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, 'i', $promotionID);
        if (!$temp_item_array)
            return null;

        $item_array = array();

        foreach($temp_item_array as &$item) {
            $item_array[] = array(
                'promotionID' => $item->promotionID,
                'couponID' => $item->couponID,
                'couponName' => $item->couponName,
                'couponNum' => $item->couponNum
            );
        }

        return $item_array;

    }


    /**
     * 会员促销发放
     * @param int $pcustID 会员号
     * @param string $custID 会员名
     * @param int $source 1、注册 2、登录 3、签到 4、建议 5、问卷调查 6、完善资料 7、商品评论
     * @return bool
     */
    public function grantCustPromotion( $pcustID, $custID, $source ) {

        global $G_SHOP;

        //查询会员促销信息
        $arg_array = array(
            'startDate' => $G_SHOP->sys_datetime,
            'source' => $source,
            'useFlg' => 1,
            'sortname' => 'promotionID',
            'sortorder' => 'DESC'
        );
        $promotion_array = $this->searchPromotionCustomerInfo( $arg_array );
        if (!$promotion_array) {
            return array( 'code' => 400, 'message' => '没有促销活动' );
        }

        $data = array(
            'points' => 0,
            'coupon' => array()
        );

        //加载优惠券类
        quanli_include('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/func/eai.func.php');

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        //实例crm类
        $crm_obj = eai_crm();

        foreach($promotion_array as &$p) {

            //检查活动领取记录（完善资料  ）
            $log_obj = new entity('promotion_customer_log');
            $log_obj->promotionID = $p['promotionID'];
            $log_obj->pcustID = $pcustID;
            if ($G_SHOP->DBCA->fetch($log_obj) && in_array($source, array(1, 2, 3, 4, 5, 6))) {
                continue;
            }
            $log_obj->creator = 'system';
            $log_obj->date = $G_SHOP->sys_date;

            if ($p['type'] == 1) { //送积分

                if (!quanli_is_int($p['points'])) {
                    continue;
                }

                //积分账户充值
                $arg_array = array(
                    'pcustID' => $pcustID,
                    'subjectId' => G_POINTS_ID,
                    'amount' => $p['points'],
                    'operator' => 'system',
                    'remark' => $p['title'] . '，积分+' . $p['points']
                );
                $crm_obj->recharge( $arg_array );

                $data['points'] += $p['points'];

            } else if ($p['type'] == 2)             { //送优惠券

                //查询需要发放的优惠券
                $coupon_array = $this->searchCustPromotionCoupon( $p['promotionID'] );
                if (!$coupon_array) {
                    continue;
                }

                //发货优惠券
                foreach($coupon_array as &$c) {

                    $c_array = array();
                    for($i = 0; $i < $c['couponNum']; $i++) {
                        $c_array[] = $custID;
                    }
                    $ebsigCoupon->createCouponCode($c['couponID'], $c_array);

                    $data['coupon'][] = sprintf('%d张%s优惠券', $c['couponNum'], $c['couponName']);

                }

            }

            $G_SHOP->DBCA->save($log_obj);

        }

        return array( 'code' => 200, 'message' => 'ok', 'data' => $data );

    }


}